<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 终端菜单权限
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container v2-group">
            <div class="handle-box">
                <el-input v-model="query.roleName" placeholder="角色名称" class="handle-input mr10" clearable></el-input>
                <el-input v-model="query.tenantId" placeholder="租户ID" class="handle-input mr10" clearable></el-input>
                <el-input v-model="query.roleAlias" placeholder="角色代码" class="handle-input mr10" clearable></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
                <!-- <el-button
                    type="success"
                    icon="el-icon-plus"
                    class="handle-del mr10"
                    @click="handleAdd"
                >新增角色</el-button> -->
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
                stripe
                row-key="id"
            >
                <!-- <el-table-column type="selection" width="55" align="center"></el-table-column> -->
                <el-table-column prop="tenantId" label="租户ID"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleAlias" label="角色代码" width="140"></el-table-column>
                <el-table-column label="排序" width="90" show-overflow-tooltip>
                    <template slot-scope="scope">{{scope.row.sort}}</template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-user-solid"
                            @click="handlePermission(scope.$index, scope.row)"
                        >权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <!-- , sizes, prev, pager, next, jumper -->
                <el-pagination
                    background
                    layout="total"
                    :current-page="query.current"
                    :page-size="query.size"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                    :page-sizes="[10, 20, 30, 40, 50, 100]"
                    @size-change="handleSizeChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%">
            <el-form ref="entityEdit" :model="form" :rules="rulesEntity" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="form.roleName"></el-input>
                </el-form-item> 
                <el-form-item label="角色代码" prop="roleAlias">
                    <el-input v-model="form.roleAlias"></el-input>
                </el-form-item> 
                <el-form-item label="上级角色" prop="parentId">
                    <el-popover
                        placement="bottom"
                        :trigger="listParent.length ? 'click' : 'manual'">
                        <div class="pop-content">
                            <div>
                                <el-tree :data="listParent" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
                            </div>
                        </div>
                        <el-input slot="reference" v-model="form.parentName"></el-input>
                    </el-popover>
                </el-form-item> 
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="form.sort"></el-input>
                </el-form-item> 
                <el-form-item label="描述" prop="remark">
                    <el-input v-model="form.remark"></el-input>
                </el-form-item> 
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :visible.sync="addVisible" width="30%">
            <el-form ref="entityAdd" :model="form" :rules="rulesEntity" label-width="80px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="form.roleName"></el-input>
                </el-form-item> 
                <el-form-item label="角色代码" prop="roleAlias">
                    <el-input v-model="form.roleAlias"></el-input>
                </el-form-item> 
                <el-form-item label="上级角色" prop="parentId">
                    <el-popover
                        placement="bottom"
                        :trigger="listParent.length ? 'click' : 'manual'">
                        <div class="pop-content">
                            <div>
                                <el-tree :data="listParent" :props="defaultProps" @node-click="handleNodeClick"></el-tree>
                            </div>
                        </div>
                        <el-input slot="reference" v-model="form.parentName"></el-input>
                    </el-popover>
                </el-form-item> 
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="form.sort"></el-input>
                </el-form-item> 
                <el-form-item label="描述" prop="remark">
                    <el-input v-model="form.remark"></el-input>
                </el-form-item> 
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 权限弹出框 -->
        <el-dialog title="权限" :visible.sync="permissionVisible" width="50%">
            <el-form :model="form" label-width="90px">
                <el-form-item label="菜单权限" prop="perms">
                    <el-checkbox-group v-model="checkList">
                        <el-checkbox :label="item.title" v-for="(item, key) in listGrant" :key="item.id"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="permissionVisible = false">取 消</el-button>
                <el-button type="primary" @click="savePermission">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { curry } from 'lodash';
import api from '../../../api/index';
export default {
    name: 'basetable',
    data() {
        return {
            query: {
                roleName: '',
                tenantId: '',
                roleAlias: '',
                current: 1,
                size: 10
            },
            tableData: [
                {
                    name: 'user01',
                    num: 21,
                    perms: '控制台',
                    update_time: '2024-11-01 00:00:00',
                }
            ],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
            addVisible: false,
            rulesEntity: {
                roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
                roleAlias: [{ required: true, message: '请输入角色代码', trigger: 'blur' }],
                sort: [{ required: true, message: '请输入排序', trigger: 'blur' }]
            },
            permissionVisible: false,
            rolePerms: {},
            checkList: [],
            permissions: [],
            permissionsRaw: [],
            listParent: [],
            defaultProps: {
                children: 'children',
                label: 'title'
            },
            treeGrant: {},
            listGrant: [],
            listGranted: []
        };
    },
    created() {
        this.getData();
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        getData() {
            api.getRoleList(this.query).then(res => {
                this.tableData = res;
                this.pageTotal = res.length;
            }).catch(err => {
                this.$message.error(err);
            });
            api.getRoleGrantTree({}).then(res => {
                this.treeGrant = res;
            }).catch(err => {
                this.$message.error(err);
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'current', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
            .then(() => {
                api.deleteRole({ids: row.id}).then(res => {
                    this.$message.success('删除成功');
                    this.getData();
                }).catch(err => {
                    this.$message.error(err);
                });
            })
            .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            this.$message.error(`删除了${str}`);
            this.multipleSelection = [];
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form = row;
            this.editVisible = true;
            this.prepareForm();
        },
        // 保存编辑
        saveEdit() {
            this.$refs.entityEdit.validate(valid => {
                if (valid) {  
                    api.saveRole(this.form).then(res => {
                        this.editVisible = false;
                        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                        this.getData();
                    }).catch(err => {
                        this.$message.error(err);
                    });
                } else {
                    return false;
                }
            });
        },
        // 新增操作
        handleAdd() {
            this.form = {};
            this.addVisible = true;
            this.prepareForm(true);
        },
        saveAdd() {
            this.$refs.entityAdd.validate(valid => {
                if (valid) {
                    api.saveRole(this.form).then(res => {
                        this.$message.success(`新增成功`);
                        this.addVisible = false;
                        this.getData();
                    }).catch(err => {
                        this.$message.error(err);
                    });
                } else {
                    return false;
                }
            });
        },
        // 权限操作
        handlePermission(index, row) {
            this.idx = index;
            this.form = row;
            this.permissionVisible = true;
            this.prepareForm();
        },
        savePermission() {
            // this.$message.info(JSON.stringify(this.checkList));
            var listOld = this.listGranted.map(m => m.id);
            if (listOld.length) {
                api.deleteComprel({ids: listOld}).then(res => {
                    this.savePermissionHelp();
                }).catch(err => {
                    this.$message.error(err);
                });
            }
            else {
                this.savePermissionHelp();
            }
        },
        savePermissionHelp() {
            if (!this.checkList.length) {
                this.permissionVisible = false;
                return;
            }
            var listNew = this.checkList.map(m => {
                var arr = this.listGrant.filter(e => e.title === m);
                var n = Object.assign({}, {type: 'tmnlmenu-role'});
                n.bId = this.form.id;//parseInt(this.form.id);
                n.aId = arr.length ? arr[0].id: 0;//arr.length ? parseInt(arr[0].id): 0;
                return n;
            });
            api.saveComprel({list: JSON.stringify(listNew)}).then(res => {
                this.$message.success(`保存成功`);
                this.permissionVisible = false;
            }).catch(err => {
                this.$message.error(err);
            });
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'current', val);
            this.getData();
        },
        handleSizeChange(val) {
            this.$set(this.query, 'size', val);
            this.getData();
        },
        prepareForm(addNew) {
            api.getCategoryList({title: '终端菜单'}).then(res => {
                if (res.length) {
                    this.categoryId = res[0].id;
                    api.getCategoryList(Object.assign({}, this.query, {parentId: this.categoryId})).then(res => {
                        this.listGrant = res;
                        api.getComprelList({type: 'tmnlmenu-role', bId: this.form.id, current: 1, size: 1000}).then(res => {
                            this.listGranted = res.records;
                            this.checkList = this.listGranted.map(m => {
                                var arr = this.listGrant.filter(e => e.id === m.aId);
                                return arr[0].title;
                            });
                        }).catch(err => {
                            this.$message.error(err);
                        });
                    }).catch(err => {
                        this.$message.error(err);
                    });
                }
            }).catch(err => {
                this.$message.error(err);
            });
        },
        handleNodeClick(data) {
            this.form.parentId = data.id;
            this.form.parentName = data.title;
            this.$forceUpdate();
            // this.$message.info(this.form.parentName);
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.pop-content > div {
    width: 30vw;
    display: flex;
    flex-wrap: wrap;
}
.pop-content > div .el-tree {
    width: 100%;
}
</style>
